// pages/address/address.js
const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    address: {
      selected: false
    },
    timer:null,
    submitted:false
  
  },
  onUnload() {
    // 页面卸载时清除定时器
    if (this.data.timer) {
      clearTimeout(this.data.timer);
      this.setData({ timer: null });
    }
  }
,
  onInputOnceSubmit(e) {
    console.log('用户输入了：', e.detail.value);
    // 这里可以保存到全局或上传服务器
  },
  getname: function (e) {
    var address = this.data.address;
    address.name = e.detail.value;
  
  
    // 设置新的定时器（延迟 300ms 执行）
    // 保存新定时器 ID 到 data
   
    const newTimer = setTimeout(() => {
    this.setData({
      address: address
    });
   console.log(address)
  },300)
  this.setData({ timer: newTimer });
  if (this.data.timer) {
    clearTimeout(this.data.timer);
  }
  },
  getphone: function (e) {
    var address = this.data.address;
    address.num = e.detail.value;
    const newTimer = setTimeout(() => {
    this.setData({
      address: address 
    });
    console.log(address);
    },300);
    this.setData({ timer: newTimer });
    if (this.data.timer) {
      clearTimeout(this.data.timer);
    }
   
  },
  /*
  getadd: function (e) {
    var address = this.data.address;
    address.aDetail = e.detail.value;
    this.setData({
      address: address
    })
  },
  */
  save: function () {
    if (this.data.timer) {
      clearTimeout(this.data.timer);
    }
    var openId = wx.getStorageSync('openId');
    var str = this.data.address;
    var name = str.name;
    console.log(name)
    var num = str.num;
    const newTimer = setTimeout(() => {
      // 延迟后执行实际逻辑
       
    if (!str.hasOwnProperty("num")) { // obj表示对象，结果为false表示不包含；否则表示包含
      wx.showModal({
        title: '提示',
        content: '请输入手机号',
        showCancel: false
      })
    } else if (str.num.length != 11) {
      wx.showModal({
        title: '提示',
        content: '请输11位号码！',
        showCancel: false
      })
    }else if (!str.hasOwnProperty("name")){
      wx.showModal({
        title: '提示',
        content: '请输入收件人！',
        showCancel: false
      })
    }else {
      db.collection('address').add({
        data: {
          str: str
        },
        success: function () {
          wx.showToast({
            title: '添加成功！',
            icon: "success",
            duration: 200
          })
        },
        fail: function () {
          wx.showToast({
            title: '提交失败！',
            icon: "error",
            duration: 800
          })
        }
      })
    }
  }, 500);
  this.setData({ timer: newTimer,
    submitted:true });
    console.log(submitted);
  },
  reSet() {
    this.setData({
      value: '',
      submitted: false
    });
  }
})